package com.atguigu.admin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 杨林
 * @create 2023-08-30 9:58 星期三
 * description:
 */

/**
 * 文件上传测试
 */
@Controller
public class FormTestController {
    
    @GetMapping("/form_layouts")
    public String formLayOut(){
        
        return "form/form_layouts";
    }


    /**
     * MultipartFile：自动封装上传来的文件
     * @param email
     * @param userName
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String userName,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
        if (!headerImg.isEmpty()){
            //保存到文件服务器
            String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File("D:\\IdeaProject\\ioTest\\headerImg\\" + originalFilename));
            if (photos.length > 0){
                for (MultipartFile photo : photos) {
                    if (!photo.isEmpty()){
                        String filename = photo.getOriginalFilename();
                        photo.transferTo(new File("D:\\IdeaProject\\ioTest\\photos\\" + filename));
                    }
                }
            }
        }
        
        return "main";
    }
    
}
